#!/usr/bin/env python3
import em
import sys
import os

def expand_template(em_file_in, file_out, context_file_path):
    # Read the template file
    with open(em_file_in, 'r') as f_in:
        template_content = f_in.read()
    
    # Create the output directory if it doesn't exist
    output_dir = os.path.dirname(file_out)
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    
    # Create a context dictionary
    context = {}
    
    # Read and execute the context file to populate the context dictionary
    try:
        with open(context_file_path, 'r') as f_ctx:
            exec(f_ctx.read(), context)
    except Exception as e:
        print(f"Error executing context file: {e}")
        sys.exit(1)
    
    # Expand the template with the context
    try:
        expanded_content = em.expand(template_content, context)
    except Exception as e:
        print(f"Error expanding template: {e}")
        sys.exit(1)
    
    # Write the expanded content to the output file
    with open(file_out, 'w') as f_out:
        f_out.write(expanded_content)
    
    print(f"Successfully expanded template '{em_file_in}' to '{file_out}'")

if __name__ == '__main__':
    if len(sys.argv) != 4:
        print("Usage: python expand_template.py <template_file> <output_file> <context_file_path>")
        sys.exit(1)
    
    em_file_in = sys.argv[1]
    file_out = sys.argv[2]
    context_file_path = sys.argv[3]
    
    expand_template(em_file_in, file_out, context_file_path)